/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filecopier.console.restore;

import java.io.File;
import java.io.IOException;
import java.util.List;
import filecopier.Singleton;
import filecopier.ActionCommand;
import filecopier.ActionCancelException;
import filecopier.script.Script;
import filecopier.script.ScriptEntry;
import filecopier.script.RestoreScript;
import filecopier.restore.FileRestoreCancelException;
import filecopier.restore.AbstractRestoreWorker;
import org.apache.log4j.Logger;
import custom.xml.DOMHelperException;

/**
 *
 * @author david
 */
public class RestoreConsoleWorker extends AbstractRestoreWorker implements ActionCommand {

    private Logger logger = null;

    public RestoreConsoleWorker(final Script restoreScript) {
        super(restoreScript);
        logger = Singleton.getInstance().getFileConsoleLogger();
    }

    public void doAction() throws ActionCancelException {
        restoreFiles();
    }

    public void restoreFiles() throws ActionCancelException {
        if (restoreScript != null) {
            List<ScriptEntry> scriptEntries = ((RestoreScript) restoreScript).getScriptEntries();
            int restoreCt = scriptEntries.size();

            try {
                for (int i = 0; i < scriptEntries.size(); i++) {
                    ScriptEntry se = scriptEntries.get(i);
                    try {
                        File restorePath = se.getPath(ScriptEntry.PathType.Restore);
                        File deletePath = se.getPath(ScriptEntry.PathType.Delete);
                        restoreFile(restorePath, deletePath);
                        logger.info("File renamed from \"" + restorePath + "\" to \"" + deletePath + "\".");
                    } catch (IOException e) {
                        logger.warn("IOException: ", e);
                        // Remove this entry from the list of ScriptEntries. This restore entry will not be
                        // removed from the script file.
                        scriptEntries.remove(se);
                        // Decrement i since we just deleted an entry and the size of the scriptEntries list will be one less.
                        i--;
                    } catch (FileRestoreCancelException e) {
                        // Remove this entry and all following entries from the list of ScriptEntries.
                        // This restore entry will not be removed from the script file.
                        for (; i < scriptEntries.size(); i++) {
                            se = scriptEntries.get(i);
                            scriptEntries.remove(se);
                        }
                        throw new ActionCancelException(e);
                    }
                }
            } finally {
                // Remove all files that were restored from the restore script. If all files were restored,
                // delete the restore script.
                if (scriptEntries.size() == restoreCt) {
                    restoreScript.getScriptFile().delete();
                    String restoreScriptName = restoreScript.getScriptName();
                    logger.info("All files in \"" + restoreScriptName + "\" were restored. \"" +
                            restoreScriptName + "\" was deleted.");
                } else {
                    ScriptEntry[] seArray = new ScriptEntry[scriptEntries.size()];
                    scriptEntries.toArray(seArray);
                    restoreScript.removeScriptEntries(seArray);
                    try {
                        restoreScript.saveToDisk();
                        logger.info(scriptEntries.size() + " out of " + restoreCt + (restoreCt == 1 ? " file was " : " files were ") +
                                "restored. All files that were restored were removed from \"" + restoreScript.getScriptName() + "\".");
                    } catch (DOMHelperException e) {
                        logger.error("RestoreScript \"" + restoreScript.getScriptName() + "\" could not be updated.", e);
                    }
                }
            }
        }
    }

    protected boolean proceed(final File restoreFile, final File deleteFile) throws FileRestoreCancelException {
        boolean restore = false;

        if (restoreFile != null && deleteFile != null) {
            boolean wrongAnswer = false;

            System.out.println("Are you sure you want to replace " + deleteFile + " with " + restoreFile +
                    "? (yes or y, yes to all or ya, no or n, no to all or na (case insensitive))");

            do {
                String answer = System.console().readLine();
                if (answer.matches("[Yy]([Ee][Ss])?")) {
                    restore = true;
                    wrongAnswer = false;
                } else if (answer.matches("[Yy]([Ee][Ss] [Tt][Oo] )?[Aa]([Ll][Ll])?")) {
                    restore = true;
                    promptForRestore = false;
                    wrongAnswer = false;
                } else if (answer.matches("[Nn][Oo]?")) {
                    restore = false;
                    wrongAnswer = false;
                } else if (answer.matches("[Nn]([Oo] [Tt][Oo] )?[Aa]([Ll][Ll])?")) {
                    throw new FileRestoreCancelException("Subsequent restore operations aborted");
                } else {
                    wrongAnswer = true;
                    System.out.println(answer + " is an invalid answer. " +
                            "Valid answers are: (yes or y, yes to all or ya, no or n, no to all or na (case insensitive)) Do you want to restore?");
                }

            } while (wrongAnswer == true);
        }

        return restore;
    }
}
